"use strict";

const Controller = require("egg").Controller;

/**
 * @controller 文章-标签接口
 */
class BlogTagController extends Controller {
  /**
   * @summary 给博客设置标签组
   * @router post /api/blog-tag/setTags
   * @request body SetTagBody 设置标签请求体
   * @apikey
   */
  async setTags() {
    const { ctx } = this;
    const { blogId, tags } = ctx.request.body;
    // 清空原标签
    await ctx.service.blogTag.destroy(blogId);
    // 设置新标签
    const promiseArr = [];
    tags.forEach(tagId => {
      const blogTag = { blogId, tagId };
      promiseArr.push(ctx.service.blogTag.create(blogTag));
    });
    ctx.body = {
      code: 200,
      msg: "给博客设置标签",
      data: await Promise.all(promiseArr),
    };
  }

  /**
   * @summary 获取博客的标签id数组,tagIds
   * @router get /api/blog-tag/getTags
   * @request query number blogId 博客id
   * @apikey
   */
  async getTags() {
    const { ctx } = this;
    const blogId = ctx.query.blogId;
    const tags = await ctx.model.BlogTag.findAll({
      where: { blogId },
    });
    const tagIds = [];
    tags.forEach(item => {
      tagIds.push(item.tagId);
    });
    ctx.body = {
      code: 200,
      msg: "获取博客的标签id数组",
      data: tagIds,
    };
  }
}

module.exports = BlogTagController;
